#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./paas/account/accounts.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
from django.conf import settings
from django.contrib.auth import logout as auth_logout, get_user_model
from django.contrib.auth.views import redirect_to_login
from django.http import HttpResponse
from django.utils.six.moves.urllib.parse import urlparse
from common.log import logger
from common.mymako import render_mako_context, render_json
from .http import http_get, http_post

class AccountSingleton(object):
    """
    单例基类.
    """
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not isinstance(cls._instance, cls):
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance


class Account(AccountSingleton):
    """
    账号体系相关的基类Account.
    提供通用的账号功能
    """
    if settings.LOGIN_DOMAIN:
        BK_LOGIN_URL = 'http://%s/login/' % settings.LOGIN_DOMAIN
    else:
        BK_LOGIN_URL = '/login/'

    def is_bk_token_valid(self, request):
        """验证用户登录态."""
        bk_token = request.COOKIES.get(settings.BK_COOKIE_NAME, None)
        if not bk_token:
            return (False, None)
        ret, data = self.verify_bk_login(bk_token, request)
        if not ret:
            return (False, None)
        username = data.get('username', '')
        user_model = get_user_model()
        try:
            user = user_model._default_manager.get_by_natural_key(username)
        except user_model.DoesNotExist:
            user = user_model.objects.create_user(username)
        finally:
            try:
                ret, data = self.get_bk_user_info(bk_token, request)
                user.chname = data.get('chname', '')
                user.company = data.get('company', '')
                user.qq = data.get('qq', '')
                user.phone = data.get('phone', '')
                user.email = data.get('email', '')
                role = data.get('role', '')
                is_superuser = True if role == '1' else False
                user.is_superuser = is_superuser
                user.is_staff = is_superuser
                user.role = role
                user.save()
            except Exception as e:
                logger.error(u'获取记录用户信息失败：%s' % e)

        return (
         True, user)

    def verify_bk_login(self, bk_token, request):
        """请求平台接口验证登录是否失效"""
        param = {'bk_token': bk_token}
        if settings.LOGIN_DOMAIN:
            verfy_url = '%saccounts/is_login/' % self.BK_LOGIN_URL
        else:
            verfy_url = '%s/login/accounts/is_login/' % settings.LOGIN_HOST
        result, resp = http_get(verfy_url, param)
        print 'xxxxxx',result
        # if resp==None:
        #     resp={}
        if result and resp:
            resp = resp if 1 else {}
            ret = resp.get('result', False)
            ret or logger.info(u'验证用户登录token无效：%s' % resp.get('message', ''))
            return (
             False, {})
        return (True, resp.get('data', {}))

    def get_bk_user_info(self, bk_token, request):
        """请求平台接口获取用户信息"""
        param = {'bk_token': bk_token}
        if settings.LOGIN_DOMAIN:
            get_user_url = '%saccounts/get_user/' % self.BK_LOGIN_URL
        else:
            get_user_url = '%s/login/accounts/get_user/' % settings.LOGIN_HOST
        result, resp = http_get(get_user_url, param)
        resp = resp if result and resp else {}
        if result and resp:
            ret = resp.get('result', False) if 1 else False
            ret or logger.error(u'请求平台接口获取用户信息失败：%s' % resp.get('message', ''))
            return (
             False, {})
        return (True, resp.get('data', {}))

    def build_callback_url(self, request, jump_url):
        callback = request.build_absolute_uri()
        login_scheme, login_netloc = urlparse(jump_url)[:2]
        current_scheme, current_netloc = urlparse(callback)[:2]
        if (not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc):
            callback = request.get_full_path()
        return callback

    def _redirect_login(self, request, is_login=True):
        """
        跳转平台进行登录
        """
        if is_login:
            callback = self.build_callback_url(request, self.BK_LOGIN_URL)
        else:
            callback = self.http_referer(request)
        return redirect_to_login(callback, self.BK_LOGIN_URL, settings.REDIRECT_FIELD_NAME)

    def redirect_login(self, request):
        """
        重定向到登录页面.
        登录态验证不通过时调用
        """
        if request.is_ajax():
            return HttpResponse(status=401)
        return self._redirect_login(request)

    def http_referer(self, request):
        """
        获取 HTTP_REFERER 头，得到登出后要重新登录跳转的url
        """
        if 'HTTP_REFERER' in request.META:
            http_referer = request.META['HTTP_REFERER']
        else:
            http_referer = settings.LOGIN_REDIRECT_URL
        return http_referer

    def logout(self, request):
        """登出并重定向到登录页面."""
        auth_logout(request)
        return self._redirect_login(request, False)

    def profile(self, request, template_name='account/profile.html'):
        """
        个人信息页面
        """
        username = request.user.username
        user_manage_url = 'http://%s/login/accounts/' % request.get_host()
        context = {'username': username,
           'chname': request.user.chname or '--',
           'qq': request.user.qq or '--',
           'phone': request.user.phone or '--',
           'email': request.user.email or '--',
           'is_superuser': request.user.is_superuser,
           'user_manage_url': user_manage_url
           }
        return render_mako_context(request, template_name, context)

    def change_password(self, request):
        """
        重置密码
        
        调用 login 系统 api 重置密码
        """
        new_password1 = request.POST.get('new_password1', '').strip()
        new_password2 = request.POST.get('new_password2', '').strip()
        if not all([new_password1, new_password2]):
            msg = u'密码不能为空'
            return render_json({'result': False,'msg': msg})
        if new_password1 != new_password2:
            msg = u'两次输入的新密码不一致'
            return render_json({'result': False,'msg': msg})
        username = request.user.username
        bk_token = request.COOKIES.get(settings.BK_COOKIE_NAME, None)
        param = {'bk_token': bk_token,'username': username,'new_password': new_password1}
        if settings.LOGIN_DOMAIN:
            request_url = '%saccounts/reset_password/' % self.BK_LOGIN_URL
        else:
            request_url = '%s/login/accounts/reset_password/' % settings.LOGIN_HOST
        result, resp = http_post(request_url, param)
        resp = resp if result and resp else {}
        if result and resp:
            ret = resp.get('result', False) if 1 else False
            return ret or render_json({'result': False,'msg': resp.get('message', u'密码重置失败')})
        return render_json({'result': True,'msg': ''})

    def show_modify_info(self, request, template_name='account/profile_modify.html'):
        """
        修改用户基本信息展示页面
        """
        return render_mako_context(request, template_name)

    def modify_user_info(self, request):
        """
        修改用户基本信息
        """
        username = request.user.username
        bk_token = request.COOKIES.get(settings.BK_COOKIE_NAME, None)
        param = {'username': username,
           'bk_token': bk_token,
           'chname': request.POST.get('chname').strip(),
           'qq': request.POST.get('qq').strip(),
           'phone': request.POST.get('phone').strip(),
           'email': request.POST.get('email').strip()
           }
        if settings.LOGIN_DOMAIN:
            request_url = '%saccounts/modify_user_info/' % self.BK_LOGIN_URL
        else:
            request_url = '%s/login/accounts/modify_user_info/' % settings.LOGIN_HOST
        result, resp = http_post(request_url, param)
        resp = resp if result and resp else {}
        if result and resp:
            ret = resp.get('result', False) if 1 else False
            return ret or render_json({'result': False,'msg': resp.get('message', u'个人信息修改失败')})
        return render_json({'result': True,'msg': ''})
